package com.zzu.base.service.impl;

import com.zzu.base.common.pojo.LoginUser;
import com.zzu.base.entity.PermissionDO;
import com.zzu.base.entity.RoleDO;
import com.zzu.base.entity.UserDO;
import com.zzu.base.service.RoleService;
import com.zzu.base.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Override
    public LoginUser loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDO userDO = userService.getUserByUsername(username);
        Long userId = userDO.getId();
        List<RoleDO> roleDOS = userService.getRolesByUserId(userId);

        List<String> roles = new ArrayList<>();
        for (RoleDO roleDO : roleDOS) {
            roles.add(roleDO.getRoleCode()); // 确保数据库中的角色代码不包含 ROLE_ 前缀
        }
        Set<String> permissionSet = new HashSet<>();
        for (RoleDO roleDO : roleDOS) {
            List<PermissionDO> rolePermissions = roleService.getPermissionsByRoleId(roleDO.getId());
            for (PermissionDO permissionDO : rolePermissions) {
                permissionSet.add(permissionDO.getPermissionCode());
            }
        }
        List<String> permissions = new ArrayList<>(permissionSet);
        LoginUser loginUser=new LoginUser(userDO,roles,permissions);
        return loginUser;
    }
}
